import torch
import torch.nn as nn
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.use('TkAgg')

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

x_data = torch.Tensor([[1.0], [2.0], [3.0]]).to(device)
y_data = torch.Tensor([[0], [0], [1]]).to(device)


class LogisticRegressionModel(nn.Module):
    def __init__(self):
        super(LogisticRegressionModel, self).__init__()
        self.linear = nn.Linear(1, 1)

    def forward(self, x):
        y_pred = torch.sigmoid(self.linear(x))
        return y_pred


model = LogisticRegressionModel().to(device)

criterion = nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

epochs = 10000
train_loss = []
for epoch in range(epochs):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    train_loss.append(loss.item())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print("epoch: {}, loss: {}".format(epoch, loss.item()))

print(model.linear.weight.item())
print(model.linear.bias.item())

x_test = torch.Tensor([[4.0]]).to(device)
y_test = model(x_test)
print("y_pred = ", y_test.data)

plt.plot(range(epochs), train_loss)
plt.grid()
plt.show()

x = np.linspace(0, 10, 1000)
x_t = torch.Tensor(x).view(-1, 1).to(device)
y_t = model(x_t)

plt.plot(x, y_t.data.cpu().numpy(), 'r')
plt.plot([0, 10], [0.5, 0.5])
plt.grid()
plt.show()

# 如果去掉 sigmoid，forward 变成 return self.linear(x)，这才是线性函数（线性回归），输出可为任意实数。
# 现在加了 sigmoid，输出被压到(0,1)，适合当作二分类的概率使用（通常配 BCEWithLogitsLoss 的 logits 版本来训练更稳定；等价地，你也可以保留 sigmoid 用 BCELoss）。
print(model)
